package it.eng.area118.mdocommon.android.util;

import it.eng.area118.mdocommon.android.log.BasicLogger;

import java.io.File;
import java.io.FileWriter;

import android.os.Environment;

public class JSONFileIO<C> {

	public static final String PATH = Environment
			.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
			.getAbsolutePath();

	public void writeObjectsFile(String filename, C obj) {
		JsonConverter jc = new JsonConverter();
		String stream = jc.convert(obj);
		writeObj(stream, filename);
	}

	public C readObjectFile(String filename, Class<C> classe) {
		JSONStringReader stringReader = new JSONStringReader();
		JsonConverter jc = new JsonConverter();
		String stream;
		try {
			stream = stringReader.readStringFromFile(PATH + "/" + filename);
			return jc.convert(classe, stream);
		} catch (Exception e) {
			BasicLogger.writeLog("JSONFileIO",
					"Error while executing readObjectFile()" + e.getMessage());
		}
		return null;
	}
	

	protected void writeObj(String jsonStream, String fileName) {
		FileWriter writer;
		
		fileName = PATH + "/" + fileName;
		try {
			if (!new File(fileName).exists()) {
				new File(fileName).createNewFile();
			}
			writer = new FileWriter(fileName, false);
			writer.write(jsonStream);
			writer.close();
		} catch (Exception e) {
			BasicLogger.writeLog("JSONFileIO",
					"Error while executing writeObj()" + e.getMessage());
		}

	}
}
